<script setup>

import {useRouter} from "vue-router";
import {computed, onMounted, reactive, ref} from "vue";
import axios from "axios";
import {Delete, InfoFilled, View} from "@element-plus/icons-vue";
import qs from "qs";
import {ElMessage} from "element-plus";

let loading = ref(false);
const router=useRouter();
let businessList=ref([]);
let dialogFormVisible=ref(false);
let form=ref({
  businessName: '',
  businessAddress: '',
  businessExplain: '',
  businessImg:'',
  starPrice: 0,
  deliveryPrice: 0
});
const formRef=ref()
let user;
let currentPage=ref(1);
let total=ref(0);
let pageSize=ref(5)
let keywords=ref('')
let avatar=ref('')
const validateNumber = (rule, value, callback) => {
  if (value === '' || isNaN(value) || Number(value) < 0) {
    callback(new Error('请输入一个大于或等于0的数字'));
  } else {
    callback();
  }
};

const rules = reactive({
  businessName: [{ required: true, message: '请输入门店名称', trigger: 'blur' }],
  businessAddress: [{ required: true, message: '请输入门店地址', trigger: 'blur' }],
  businessExplain: [{ required: true, message: '请输入经营类型', trigger: 'blur' }],
  businessImg: [{ required: true, message: '请上传头像', trigger: 'blur' }],
  starPrice: [
    { required: true, message: '请输入起送价', trigger: 'blur' },
    { validator: validateNumber, trigger: 'blur' }
  ],
  deliveryPrice: [
    { required: true, message: '请输入配送价', trigger: 'blur' },
    { validator: validateNumber, trigger: 'blur' }
  ]
});


onMounted( () => {
  // user = JSON.parse(sessionStorage.getItem("user"));
  getBusinessList();

  // console.log(pagedShopList.value);
})

const ok = () => {
  ElMessage({
    message: '删除成功!',
    type: 'success',
  })
}

const error = () => {
  ElMessage({
    message: '删除失败!',
    type: 'error',
  })
}

function getBusinessList() {
  loading.value=true
  axios.get("/admin/getAllBusiness",
      {
          params: {pageSize:pageSize.value,
          pageNum:currentPage.value
        }
      }).then(res=>{

    console.log(res.data)
    businessList.value=res.data.list
    total.value=res.data.totalCount
    }).catch(err=>{

    }).finally(()=>{
      loading.value=false
    })
}

function add(){
  dialogFormVisible.value = true
  form.value={}
}

async function save(fr) {
  if (!fr) return
  await fr.validate( async (valid) => {
    // console.log(valid,666)
    if (valid) {
      const response = await axios.post('/admin/createBusiness', form.value);
      dialogFormVisible.value = false;
      getBusinessList();
      ElMessage.success('保存成功');
    } else {
      ElMessage.error('请填写完整的表单信息');
    }
  });

  // console.log(form.value)
  // const response = await axios.post("/admin/createBusiness", form.value)
  // console.log(response)
  // dialogFormVisible.value = false
  // getBusinessList()
}

async function deleteShop(businessId) {
  const requestData = {
      businessId: businessId,
  };
  // console.log(requestData)
   await axios.post("/admin/deleteBusiness",requestData).then(res=>{
     console.log(res)
     ok();
   }).catch(err=>{
     error()
     console.log(err);
   })

  getBusinessList()
}
function handleSizeChange(newSize){
  pageSize.value=newSize
  getBusinessList()
}
function handleCurrentChange(newPage){
  // console.log(newPage)
  currentPage.value=newPage
  getBusinessList()
}
async function search() {
  const response = await axios.get("/admin/getAllBusiness",
      {
        params: {
          pageSize: pageSize.value,
          pageNum: currentPage.value,
          keywords:keywords.value
        }
      });
  console.log(response.data)
  businessList.value = response.data.list
  total.value = response.data.totalCount

}

function clean(){
  keywords.value=''
  getBusinessList();
}
const updateAvatar = (event) => {
  const file = event.target.files[0];
  if (file) {
    const isImage = file.type.startsWith('image/');
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isImage) {
      ElMessage.error('上传的文件必须是图片!');
      return;
    }
    if (!isLt2M) {
      ElMessage.error('上传的图片大小不能超过 2MB!');
      return;
    }

    // avatar.value = file;
    avatar.value = URL.createObjectURL(file);// 用于预览
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      // avatar.value = reader.result; // Base64 编码
      // console.log(avatar.value)
      form.value.businessImg = reader.result;
    };
    reader.onerror = () => {
      ElMessage.error('文件读取失败');
    };

  }
  // 清空文件输入元素的值，以便再次选择相同的文件时能够触发 change 事件
  event.target.value = '';
}
function gotoBusinessInfo(businessId){
  console.log(router.currentRoute.value)
  router.push({
    path: '/admin/businessInfo',
    query: { businessId: businessId }
  });
}

</script>

<template>
  <div style="margin: 10px 0">
    <el-input style="width: 400px;margin: 10px 5px" placeholder="请输入名称" suffix-icon="el-icon-search" v-model="keywords"></el-input>
    <el-button type="primary" style="margin-left: 5px;" @click="search">搜索 <i
        class="el-icon-search"></i></el-button>
    <el-button type="primary" style="margin-left: 5px;" @click="clean">清除 <i class="el-icon-refresh"></i>
    </el-button>
    <el-button type="primary" @click="add">新增 <i class="el-icon-circle-plus-outline"></i></el-button>
  </div>

  <el-table :data="businessList" border stripe v-loading="loading">

    <el-table-column prop="businessId" label="ID" >
    </el-table-column>
    <el-table-column prop="businessName" label="门店名" >
    </el-table-column>

    <el-table-column label="操作" >
      <template #default="scope">
        <el-button type="success" @click="gotoBusinessInfo(scope.row.businessId)"><el-icon style="margin-right: 3px" ><View /></el-icon> 查看</el-button>
      <el-popconfirm
          width="220"
          confirm-button-text="OK"
          cancel-button-text="No, Thanks"
          :icon="InfoFilled"
          icon-color="#626AEF"
          title="确认删除吗?"
          @confirm="deleteShop(scope.row.businessId)"
      >
        <template #reference>
          <el-button type="danger" ><el-icon style="margin-right: 3px"><Delete /></el-icon> 删除</el-button>
        </template>
      </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
<!--  <div style="padding: 10px 30px">-->
<!--    <el-pagination-->
<!--        @size-change="handleSizeChange"-->
<!--        @current-change="handleCurrentChange"-->
<!--        :current-page="pageNum"-->
<!--        :page-sizes="[2, 5, 10, 20]"-->
<!--        :page-size="pageSize"-->
<!--        layout="total, sizes, prev, pager, next, jumper"-->
<!--        :total="total">-->
<!--    </el-pagination>-->
<!--  </div>-->

  <el-dialog v-model="dialogFormVisible" title="新增门店">
    <el-form :model="form" :rules="rules" ref="formRef">
      <el-form-item label="头像上传" prop="businessImg">
        <el-image :src="form.businessImg" class="image_1" style="border-radius: 3px 3px 0 0">
          <template #error>
            <div class="error">暂无头像</div>
          </template>
        </el-image>
        <el-button style="margin-left: 20px" @click="$refs.upload.click()">上传头像
          <input
              ref="upload"
              style="display: none"
              name="file"
              type="file"
              @change="updateAvatar"
          />
        </el-button>
      </el-form-item>
      <el-form-item label="门店名称" :label-width="80" prop="businessName">
        <el-input v-model="form.businessName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="门店地址" :label-width="80" prop="businessAddress">
        <el-input v-model="form.businessAddress" autocomplete="off" />
      </el-form-item>
      <el-form-item label="经营类型" :label-width="80" prop="businessExplain">
        <el-input v-model="form.businessExplain" autocomplete="off" />
      </el-form-item>
      <el-form-item label="起送价" :label-width="80" prop="starPrice">
        <el-input v-model="form.starPrice" autocomplete="off"  />
      </el-form-item>
      <el-form-item label="配送价" :label-width="80" prop="deliveryPrice">
        <el-input v-model="form.deliveryPrice" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false;avatar.value=''">Cancel</el-button>
        <el-button type="primary" @click="save(formRef)">
          Confirm
        </el-button>
      </span>
    </template>
  </el-dialog>
  <div class="example-pagination-block">

    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20]"
        layout="total,sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
</template>

<style scoped>

.card{
  width: 100%;
}
.card .image{
  width: 100px;
  height: 100px;
}


.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
  margin-right: 5px;
}



.example-pagination-block{
  display: flex;
  justify-content: center;
  margin-top: 50px;
}
.image_1 {
  width: 275px;
  height: 260px;
  background: #ffffff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.error {
  margin: 100px auto;
  width: 50%;
  padding: 10px;
  text-align: center;
}
</style>